<?php
namespace app\forms;

use yii\base\Model;
use app\models\User;
use yii\db\Expression;
class UserCreateForm extends Model
{
    const ERROR_USER_NAME_EXISTS = '用户名已存在';
    
    public $username;
    public $password;
    
    public function rules() {
        return [
            [['username', 'password'], 'required'],
            ['username', 'checkUsername']
        ];
    }
    
    public function checkUsername() {
        $exists = User::find()->where(['username' => $this->username])->exists();
        if ($exists) {
            $this->addError('username', self::ERROR_USER_NAME_EXISTS);
        }
    }
    
    /**
     * 创建一个用户
     * @return \app\models\User
     */
    public function create() {
        $user = new User();
        $user->username = $this->username;
        $user->password = \Yii::$app->security->generatePasswordHash($this->password);
        $user->createTime = new Expression('now()');
        $user->save();
        
        return $user;
    }
}

?>